package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.service.TestService;
import com.atguigu.tingshu.common.constant.RedisConstant;
import org.redisson.Redisson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author dxt
 * @create 2025-06-27-17:03
 */
@Service
public class TestServiceImpl implements TestService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private Redisson redisson;


    /**
     * 测试分布式锁
     *
     */
    @Override
    public void testLock() {

        /*String uuid = UUID.randomUUID().toString();
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 3000, TimeUnit.MILLISECONDS);
        if (ifAbsent){
            String key = "num";
            String value = redisTemplate.opsForValue().get(key).toString();
            redisTemplate.opsForValue().set(key, Integer.parseInt(value) + 1);
            if (uuid.equals(redisTemplate.opsForValue().get("lock"))){
                redisTemplate.delete("lock");
            }
        }else {
            try {
                Thread.sleep(100);
                this.testLock();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }*/

        redisson.getLock("lock").lock();
          try {
              String key = "num";
              String value = redisTemplate.opsForValue().get(key).toString();
              redisTemplate.opsForValue().set(key, Integer.parseInt(value) + 1);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                redisson.getLock("lock").unlock();
            }

    }
}
